package com.zadtek.shopmall.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.zadtek.shopmall.Event.EventTest;
import com.zadtek.shopmall.R;
import com.zadtek.shopmall.base.AbsActivity;
import com.zadtek.shopmall.bean.LoginResponse;
import com.zadtek.shopmall.net.BaseObserver;
import com.zadtek.shopmall.net.BaseResponse;
import com.zadtek.shopmall.net.NetTool;
import com.zadtek.shopmall.other.Const;
import com.zadtek.shopmall.utils.MD5;
import com.zadtek.shopmall.utils.RegexUtils;
import com.zadtek.shopmall.utils.SPUtil;
import com.zadtek.shopmall.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class RegsisterActivity extends AbsActivity implements View.OnClickListener {

    private EditText etPhoneNumber,etSmsCode,etPassWord,etUsername;
    private TextView tvSendCode,tvRegsister,tvUserAgreement,tvTopTitle;
    private ImageView ivBack;

    @Override
    public int setView() {
        return R.layout.activity_regsister;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        initView();
        initLogic();
        updateVew();
    }

    private void updateVew() {
        tvTopTitle.setText("快速注册");
        ivBack.setVisibility(View.VISIBLE);
    }

    private void initLogic() {
        ivBack.setOnClickListener(this);
        tvSendCode.setOnClickListener(this);
        tvRegsister.setOnClickListener(this);
        tvUserAgreement.setOnClickListener(this);
    }

    private void initView() {
        etPhoneNumber = (EditText) findViewById(R.id.et_phonenumber);
        etSmsCode = (EditText) findViewById(R.id.et_smscode);
        etPassWord = (EditText) findViewById(R.id.et_password);
        tvSendCode = (TextView) findViewById(R.id.tv_send_smscode);
        tvRegsister = (TextView) findViewById(R.id.tv_regsister);
        etUsername = findViewById(R.id.et_username);
        tvUserAgreement = (TextView) findViewById(R.id.tv_user_agreement);
        tvTopTitle = (TextView)findViewById(R.id.title);
        ivBack = (ImageView)findViewById(R.id.ic_back);
    }

    @Override
    public void onClick(View view) {
        String phoneNumber = etPhoneNumber.getText().toString();
        String smsCode = etSmsCode.getText().toString();
        String password = etPassWord.getText().toString();
        String username = etUsername.getText().toString();
        switch (view.getId()){
            case R.id.tv_send_smscode:
                if(TextUtils.isEmpty(phoneNumber)&& RegexUtils.isPhone(phoneNumber)){
                    ToastUtil.showToast("请填写正确的手机号！");
                    break;
                }
                sendSmsCodeRequest(phoneNumber);
                break;
            case R.id.tv_regsister:
                if(TextUtils.isEmpty(username)){
                    ToastUtil.showToast("请填写用户名！");
                    break;
                }
                if(TextUtils.isEmpty(phoneNumber)){
                    ToastUtil.showToast("请填写正确的手机号！");
                    break;
                }
                if(TextUtils.isEmpty(smsCode)){
                    ToastUtil.showToast("请填写验证码！");
                    break;
                }
                if(TextUtils.isEmpty(password)){
                    ToastUtil.showToast("请填写密码！");
                    break;
                }
                regsisterRequest();
                break;
            case R.id.tv_user_agreement:
                Intent intent = new Intent(this,WebActivity.class);
                intent.putExtra(WebActivity.URL,"http://xmlife.zadtek.com/mobile/index.php?m=article&a=detail&id=6");
                intent.putExtra(WebActivity.TITLE,"用户协议");
                startActivity(intent);
                break;
            case R.id.ic_back:
                finish();
                break;
        }
    }

    private void regsisterRequest() {
        String phonenumber = etPhoneNumber.getText().toString();
        String smscode = etSmsCode.getText().toString();
        String password = etPassWord.getText().toString();
        String username = etUsername.getText().toString();
        Map<String, Object> params = NetTool.newParams();
        params.put("username",username);
        params.put("phoneNumber",phonenumber);
        params.put("smsCode",smscode);
        params.put("password", MD5.getStringMD5(password));
        NetTool.getApi().register(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResponse<LoginResponse>>() {
                    @Override
                    public void accept(BaseResponse<LoginResponse> baseResponse) throws Exception {
                        if (baseResponse.getCode() == 0 && baseResponse.getData().isSuccess()) {
                            LoginResponse response = baseResponse.getData();
                            ToastUtil.showToast("注册成功！");
                            SPUtil.saveDate(RegsisterActivity.this, Const.IsLogin, true);
                            SPUtil.saveDate(RegsisterActivity.this, Const.UserId, response.getUid());
                            SPUtil.saveDate(RegsisterActivity.this, Const.UserToken, response.getUsertoken());
                            Const.userid = response.getUid();
                            Const.token = response.getUsertoken();
                            Const.isLogin = true;
                            Const.loginYM();
                            finish();
                            EventBus.getDefault().post(new EventTest(EventTest.LOGIN));
                        }else{
                            ToastUtil.showToast(baseResponse.getData().getFailMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtil.showToast(throwable.getLocalizedMessage());
                    }
                });
    }

    private void sendSmsCodeRequest(String phoneNumber) {
        Map<String, Object> params = NetTool.newParams();
        params.put("phonenumber",phoneNumber);
        NetTool.getApi().getsmscode(params)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new BaseObserver<BaseResponse<LoginResponse>>() {
                @Override
                public void onData(BaseResponse<LoginResponse> value) {
                    if(value.getCode() == 0 && value.getData().isSuccess()){
                        ToastUtil.showToast("发送验证码成功！");
                        startCountDown();
                    }else{
                        //ToastUtil.showToast("发送验证码出错！");
                        startCountDown();
                    }
                }
            });
    }

    private void startCountDown() {
        tvSendCode.setClickable(false);
        CountDownTimer timer = new CountDownTimer(60000,1000) {
            @Override
            public void onTick(long l) {
                tvSendCode.setText(l/1000+"s");
            }
            @Override
            public void onFinish() {
                tvSendCode.setText("发送");
                tvSendCode.setClickable(true);
            }
        };
        timer.start();
    }
}
